/**
 * vueuse的useCountdown没反应
 */

import { onUnmounted, Ref, shallowRef, ShallowRef, unref } from "vue";

export default (initValue: number | Ref<number> | ShallowRef<number>) => {
  const val = shallowRef(initValue);

  let timer;
  const run = () => {
    timer = setInterval(() => {
      val.value--;

      if (val.value <= 0) clear();
    }, 1000);
  };

  const clear = () => clearInterval(timer);

  const start = (nextValue?: number) => {
    if (nextValue && nextValue > 0) {
      val.value = nextValue;
    }

    run();
  };

  onUnmounted(() => clear());

  return {
    start,
  };
};
